package com.elvish.oda.busin.controller;

import java.util.List;

import org.nutz.lang.Lang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import com.elvish.oda.busin.pojo.Area;
import com.elvish.oda.busin.service.AreaService;
import com.elvish.oda.common.pojo.Result;
import com.elvish.oda.common.utils.CommonUtil;
import com.elvish.oda.common.utils.ResultUtil;

@RestController
public class AreaController {

	@Autowired
	private AreaService areaService;

	/**
	 * 初始化地域tree表格
	 * 
	 * @return easyui tree表格数据
	 */
	@PostMapping(value = "/area/initAreaTreeTable")
	public List<Area> initAreaTreeTable() {
		List<Area> areas = areaService.findAll();
		if (areas != null && areas.size() > 0) {
			List<Area> treeList = CommonUtil.buildTree(areas, "pid");
			return treeList;
		}
		return null;
	}

	/**
	 * 操作地域
	 * 
	 * @return easyui tree表格数据
	 */
	@PostMapping(value = "/area/operArea/{oper}")
	public Result<Area> operArea(Area area, @PathVariable("oper") Integer operFlag) {
		Result result = new Result<>();
		try {

			if (operFlag == 1) {
				// 新增
				if (Lang.isEmpty(area.getId())) {
					areaService.save(area);
				}
				// 更新
				else {
					areaService.update(area);
				}
			}
			// 删除
			else if (operFlag == 2) {
				areaService.deleteById(area.getId());
			}
			result = ResultUtil.success();
		} catch (Exception e) {
			result = ResultUtil.fail(-1, "系统异常");
		}
		return result;
	}

}
